#!/usr/bin/env python3
"""
最终系统状态验证
"""

import sys
import os

def check_system_status():
    """检查系统整体状态"""
    print("=== 系统状态检查 ===")
    
    status = {
        "chromadb_installed": False,
        "chromadb_detected": False,
        "fallback_ready": False,
        "knowledge_base_working": False
    }
    
    # 1. 检查ChromaDB安装
    try:
        import chromadb
        status["chromadb_installed"] = True
        print("✅ ChromaDB 已安装")
    except ImportError:
        print("⚠️  ChromaDB 未安装")
    
    # 2. 检查系统检测
    try:
        from utils.chroma_db import HAS_CHROMADB
        status["chromadb_detected"] = HAS_CHROMADB
        print(f"✅ 系统检测: HAS_CHROMADB = {HAS_CHROMADB}")
    except Exception as e:
        print(f"❌ 系统检测失败: {e}")
    
    # 3. 测试回退机制
    try:
        from utils.chroma_db import KnowledgeChromaDB
        
        # 强制测试回退
        test_kb = KnowledgeChromaDB("status_test")
        
        if hasattr(test_kb, 'mode'):
            print(f"✅ 运行模式: {test_kb.mode}")
            
            # 测试添加数据
            test_data = [{"question": "状态测试", "answer": "系统状态正常"}]
            test_kb.batch_add_qa_pairs(test_data)
            print("✅ 数据添加成功")
            
            # 测试搜索
            results = test_kb.search_question("状态")
            print(f"✅ 搜索成功，找到 {len(results)} 个结果")
            
            # 测试统计
            stats = test_kb.get_stats()
            print(f"✅ 统计信息: {stats}")
            
            status["knowledge_base_working"] = True
            status["fallback_ready"] = True
            
        else:
            print("❌ 无法确定运行模式")
            
    except Exception as e:
        print(f"❌ 回退机制测试失败: {e}")
        import traceback
        traceback.print_exc()
    
    return status

def check_requirements():
    """检查依赖包"""
    print("\n=== 依赖包检查 ===")
    
    required_packages = [
        "chromadb",
        "numpy", 
        "openai",
        "requests",
        "sentence_transformers",
        "scikit-learn"
    ]
    
    missing = []
    for package in required_packages:
        try:
            __import__(package)
            print(f"✅ {package}")
        except ImportError:
            print(f"⚠️  {package} (未安装)")
            missing.append(package)
    
    return len(missing) == 0

def main():
    """主函数"""
    print("🔍 开始最终系统状态检查")
    print("="*60)
    
    # 检查系统状态
    status = check_system_status()
    
    # 检查依赖
    deps_ok = check_requirements()
    
    # 输出总结
    print("\n" + "="*60)
    print("📋 最终系统状态报告")
    print("="*60)
    
    print(f"   ChromaDB安装状态: {'✅ 已安装' if status['chromadb_installed'] else '⚠️  未安装'}")
    print(f"   系统检测状态: {'✅ 正常' if status['chromadb_detected'] else '❌ 异常'}")
    print(f"   回退机制: {'✅ 就绪' if status['fallback_ready'] else '❌ 故障'}")
    print(f"   知识库功能: {'✅ 正常' if status['knowledge_base_working'] else '❌ 故障'}")
    print(f"   依赖包: {'✅ 完整' if deps_ok else '⚠️  缺失'}")
    
    print("\n💡 系统状态:")
    
    if status['chromadb_installed'] and status['chromadb_detected']:
        print("   🎉 ChromaDB已成功安装并集成")
        print("   💡 系统将使用ChromaDB作为向量数据库")
    elif status['fallback_ready']:
        print("   ⚠️  ChromaDB遇到问题")
        print("   ✅ 但回退机制正常工作")
        print("   💡 系统使用备用向量数据库方案")
    else:
        print("   ❌ 系统存在严重问题")
        print("   🔧 需要检查错误日志")
    
    print("\n" + "="*60)
    
    # 总体评估
    if status['knowledge_base_working']:
        print("🎉 系统总体状态: ✅ 正常")
        print("💡 聊天应用可以正常运行")
        return 0
    else:
        print("❌ 系统总体状态: ⚠️  异常")
        print("🔧 需要进一步排查问题")
        return 1

if __name__ == "__main__":
    sys.exit(main())